import { Dropdown, InputNumber, MenuProps, Table } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import { ContextType, TableData, TableProps } from '../type';

const createEmptyRow = (): TableData => ({
  key: 0,
  height: null,
  angles: null,
  thickness: null,
});

export function TableComponent({
  selectedKey: initSelectedKey,
  initialData,
  onDataChange,
}: TableProps) {
  const [dataSource, setDataSource] = useState<TableData[]>([createEmptyRow()]);
  const [selectedKey, setSelectedKey] = useState<number>(-1);
  const currentEditKey = useRef<number>(-1);
  const tableRef = useRef<{
    nativeElement: HTMLDivElement;
    scrollTo: (config: {
      key?: React.Key;
      index?: number;
      top?: number;
    }) => void;
  }>(null);
  useEffect(() => {
    onDataChange?.(
      dataSource,
      currentEditKey.current >= 0 ? currentEditKey.current : undefined,
    );
    currentEditKey.current = -1;
  }, [dataSource]);
  useEffect(() => {
    setSelectedKey(initSelectedKey);
    if (initSelectedKey >= 0) {
      tableRef.current?.scrollTo({ key: initSelectedKey });
    }
  }, [initSelectedKey]);
  useEffect(() => {
    if (initialData && initialData.length === 0) {
      setDataSource([createEmptyRow()]);
    } else {
      setDataSource((prev) => {
        const lastRow = prev[prev.length - 1]; //获取最后一行
        // 判断当前最后一行是不是空的
        const isLastRowEmpty =
          lastRow &&
          lastRow.height === null &&
          lastRow.angles === null &&
          lastRow.thickness === null;
        let newData = prev;
        if (isLastRowEmpty) {
          // 如果最后一行是空的，覆盖它（保留 key）
          newData = prev.slice(0, -1);
        }
        return [...newData, ...initialData].map((item, index) => ({
          ...item,
          key: index,
        }));
      });
      // 说明导入了 csv 文件
    }
  }, [initialData]);

  const EditableCell = ({ value, onChange, recordKey, dataIndex }) => {
    return (
      <InputNumber
        key={`${recordKey}-${dataIndex}`}
        value={value}
        onChange={(val) => {
          onChange(val);
        }}
        size='small'
        className='w-full'
      />
    );
  };
  const contextMenu = [
    {
      key: ContextType.InsertRowAbove,
      label: '向上插入一行',
    },
    {
      key: ContextType.InsertRowBelow,
      label: '向下插入一行',
    },
    {
      key: ContextType.DeleteRow,
      label: '删除选中行',
    },
    {
      key: ContextType.DeleteAll,
      label: '删除所有行',
    },
  ];
  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    const currentIndex = dataSource.findIndex(
      (item) => item.key === selectedKey,
    );
    if (currentIndex === -1) {
      return;
    }
    switch (key) {
      case ContextType.InsertRowAbove:
        setDataSource((prev) => {
          const newList: TableData[] = [
            ...prev.slice(0, currentIndex),
            createEmptyRow(),
            ...prev.slice(currentIndex),
          ];
          // 调整key
          for (let i = 0; i < newList.length; i++) {
            newList[i].key = i;
          }
          return newList;
        });
        break;
      case ContextType.InsertRowBelow:
        setDataSource((prev) => {
          const newList: TableData[] = [
            ...prev.slice(0, currentIndex + 1),
            createEmptyRow(),
            ...prev.slice(currentIndex + 1),
          ];
          // 调整key
          for (let i = 0; i < newList.length; i++) {
            newList[i].key = i;
          }
          return newList;
        });
        break;
      case ContextType.DeleteRow:
        setDataSource((prev) => {
          const newList = prev.filter((item) => item.key !== selectedKey);
          // 至少保留一行
          newList.length === 0 && newList.push(createEmptyRow());
          // 调整key
          newList.forEach((item, index) => (item.key = index));
          return [...newList];
        });
        break;
      case ContextType.DeleteAll:
        setDataSource([createEmptyRow()]);
        break;
    }
  };

  const rowNumberColumn = {
    title: '#',
    width: 60,
    align: 'center' as const,
    render: (_: any, __: TableData, index: number) => {
      return index + 1;
    },
  };
  const columns = useMemo(
    () => [
      rowNumberColumn,
      ...[
        {
          key: 'height',
          title: '截面值',
        },
        {
          key: 'angles',
          title: '周向角',
        },
        {
          key: 'thickness',
          title: '厚度',
        },
      ].map((col) => {
        return {
          title: col.title,
          dataIndex: col.key.toLowerCase(),
          key: col.key.toLowerCase(),
          align: 'center' as const,
          render: (text, record: TableData) => {
            return (
              <EditableCell
                recordKey={record.key}
                dataIndex={col.key.toLowerCase()}
                value={text}
                onChange={(value) => {
                  currentEditKey.current = record.key;
                  setDataSource((prev) => {
                    const data = prev.map((item) =>
                      item.key === record.key
                        ? { ...item, [col.key.toLowerCase()]: value }
                        : item,
                    );
                    return data;
                  });
                }}
              />
            );
          },
        };
      }),
    ],
    [],
  );
  return (
    <>
      <Dropdown
        menu={{
          items: contextMenu,
          onClick: handleMenuClick,
        }}
        // open={!!selectedKey}
        onOpenChange={(open) => {
          if (!open) {
            setSelectedKey(-1);
          }
        }}
        placement='bottom'
        trigger={['contextMenu']}>
        <div
          onContextMenu={(e) => {
            e.preventDefault();
          }}>
          <Table
            ref={tableRef}
            dataSource={dataSource}
            columns={columns}
            rowKey='key'
            rowSelection={{
              selectedRowKeys: [selectedKey],
              columnWidth: 0, // 把选择框那一列宽度设为 0
              renderCell: () => null, // 不渲染选择框
            }}
            onRow={(record) => ({
              onContextMenu: (e) => {
                e.preventDefault();
                setSelectedKey(record.key);
              },
            })}
            scroll={{ y: 'calc(80vh - 250px)' }}
            pagination={false}
            bordered
            size='small'
            className='custom-table-style'
          />
        </div>
      </Dropdown>
    </>
  );
}
